<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js" ></script>
</head>
  <body>
<style>
.fieldRow{
 display:block;
}
</style>
<script>
$(document).ready(function(){

doLoad("#list", "{{ basePath }}/list", loadRows);
doLoad("#add","{{ basePath }}/add", allDataLoaded);


});

function loadRows(){

	$(".fieldPlaceholder").each(function(){
	loadRow(this);
	});
}

function loadRow(placeholder){
	var keyId = $(placeholder).prev("input[name='keyId']").val();
	doLoad(placeholder, "{{ basePath }}/list?storeKey=" + keyId);
}

function doLoad(placeholder, url, callback){
	if (callback){

   		$(placeholder).load(url, callback);

     } else {
		$(placeholder).load(url);
     }
}


function allDataLoaded(){
$(".editButton").click(function(){
	showAllReadOnly();
	loadEditForm($(this));	        
	return false;
});

}

function showAllReadOnly(){
$(".field").show();	
$(".buttonPanel").show();	
	$("#loading").hide();		
	$("#edit").hide();		
}

function wireUpSaveCancel(){

$(".okButton").click(function(){

	var $frm = $(this).closest(".editForm");
	var $row = $(this).closest(".fieldRow");
	postForm($frm.attr("action"), $frm, function(){
			toggleEditModeOff($row);
		});


	
	return false;
});

$(".cancelButton").click(function(){
	var $row = $(this).closest(".fieldRow");
	toggleEditModeOff($row);

	return false;
});

}

function loadEditForm($obj){
	var $row = $obj.closest(".fieldRow")
	$("#loading").show();
	var editPlaceholder = "#edit";
	$row.append($("#loading"));	
	$obj.closest(".buttonPanel").hide();
	$(editPlaceholder).hide();
	var url= $obj.attr("href");
     doLoad(editPlaceholder, url, function(){
			toggleEditModeOn($(this), $row);
		});    

}

function postForm(url, $frm, callback){
	if (callback){
		$.post(url, $frm.serialize(), function(){
			callback();
		});
	} else {
		$.post(url, $frm, serialize());
	}

}

function toggleEditModeOn($obj, $row){
$row.find(".field").hide();
	$row.append($obj); 
	$obj.show(); 	
	$("#loading").hide();
	wireUpSaveCancel();
}

function toggleEditModeOff($row){
loadRow($row.find(".fieldPlaceholder")[0]);

	$("#edit").hide();
	$(".field").show();
	$row.find(".buttonPanel").show();  
	$("#loading").hide();

}


</script>
    <div id="loading" style="display:none;">{{ loadingHtml }}</div>

    <div id="list">{{ loadingHtml }}</div>

        
    <div id="edit"></div>

    <div id="add">{{ loadingHtml }}</div>



    <a href="{{ url }}">{{ url_linktext }}</a>

  </body>
</html>